<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Objects extends CI_Controller {

        function __construct(){
            parent::__construct();
            $this->load->model('objects_model');
            $this->load->model('codegen_model');
        }

        function index() { show_404(); }

        function view_edit($object_ID){

            $this->load->model('owners_model');

            $this->data['title'] = "Uredi objekat";    
            $this->data['post_action'] = "EDIT";     
            $this->data['owners'] = $this->owners_model->view_all_owners();
            $this->data['destinations'] = $this->objects_model->view_all_posts('resort');
            $this->data['object'] = $this->objects_model->view_edit($object_ID);
            //$this->firephp->log($this->db->last_query());
            echo $this->load->view('objects/edit_object',$this->data,TRUE);

        }

        function view_new(){

            $this->load->model('owners_model');

            $this->data['title'] = "Novi objekat";
            $this->data['post_action'] = "NEW";
            $this->data['owners'] = $this->owners_model->view_all_owners();
            $this->data['destinations'] = $this->objects_model->view_all_posts('resort');

            //$this->data['attributes'] = $this->codegen_model->get('attributes','*',"custom = 1",999999);
            //$this->firephp->log($this->db->last_query());

            echo $this->load->view('objects/edit_object',$this->data,TRUE);

        }

        function view_all(){

            $this->data['title'] = "Hotels";
            //$this->data['objects'] = $this->objects_model->view_all(); 
            $this->data['objects'] = Model\Objects::all(); 
            //$this->data['fields'] = $this->objects_model->get_fields();
            $this->template->build('objects/view_all_objects',$this->data); 

        }

        function submit_post(){

            /*General*/
            if($_POST['editObjectDialog_post_action']=='NEW'):
                $this->form_validation->set_rules('editObjectDialog_object_type', 'type', 'callback_dropdown_check'); 
                endif;
            $this->form_validation->set_rules('editObjectDialog_owner', 'supplier', 'callback_dropdown_check'); 
            $this->form_validation->set_rules('name', 'name', 'required');

            /*Custom*/
            $q = 'SELECT oa.ID, oa.type, oa.custom, a.ID as att_ID, a.name, a.value, a.required, a.custom
            FROM object_attributes as oa
            LEFT JOIN attributes as a ON oa.attributes_ID = a.ID
            WHERE oa.type = "'.$_POST['editObjectDialog_object_type'].'" AND oa.custom = 1 AND a.required = 1
            ORDER BY oa.order ASC, oa.custom ASC, oa.ID ASC 
            '; 

            $object_attributes = $this->db->query($q)->result_array();

            /*Trace code*/
            //$this->firephp->log($this->db->last_query());
            //$this->firephp->log($object_attributes);

            $this->load->helper('inflector');

            foreach ($object_attributes as $object_attribute):
                $name_id = preg_replace('/[^a-zA-Z0-9_%\[().\]\\/-]/s', '', camelize($object_attribute['name']));
                $this->form_validation->set_rules($name_id, $object_attribute['name'], 'required');
                endforeach;

            $this->form_validation->set_message('required','Please enter object <b>%s</b>!');

            if ($this->form_validation->run('object_attributes') == FALSE)
            {
                echo json_encode(array('action'=>FALSE, 'msg'=>validation_errors()));
            } 
            else
            {                            

                //Start entering Object
                //For custom fields we use serialize
                //a:8:{s:13:"numberOfStars";s:7:"5 stars";s:18:"distanceFromTheSea";s:5:"400 m";s:21:"distanceFromTheCenter";s:4:"1 km";s:12:"contactPhone";s:0:"";s:10:"contactFax";s:0:"";s:7:"address";s:0:"";s:14:"searchPriority";s:0:"";s:9:"infantAge";s:0:"";}



                $post_action = $_POST['editObjectDialog_post_action'];
                $record['type'] = $_POST['editObjectDialog_object_type'];
                $destination = $_POST['editObjectDialog_destination']; 
                $record['owners_ID'] = $_POST['editObjectDialog_owner'];;
                $record['name'] = $_POST['name'];
                $record['status'] = 1;
                $record['date_time'] = time();                

                unset($_POST['editObjectDialog_post_action']);
                unset($_POST['editObjectDialog_object_type']);
                unset($_POST['editObjectDialog_destination']);
                unset($_POST['editObjectDialog_owner']);
                unset($_POST['name']);

                //$this->firephp->info($_POST);
                //exit;

                switch ($post_action) {
                    case 'NEW':
                        $record['fields'] = serialize($_POST);
                        $this->firephp->info($record);
                        $this->db->insert('objects',$record);

                        if ($this->db->affected_rows() == '1')
                        {
                            echo json_encode(array('action'=>true,'msg'=>'Successful insert operation.'));
                        }else
                        {
                            echo json_encode(array('action'=>FALSE, 'msg'=>'<p>An Error Occured.</p>')); 
                        }
                        break;
                    case 'EDIT':
                        $object_ID = $_POST['editObjectDialog_post_ID'];
                        unset($_POST['editObjectDialog_post_ID']);
                        
                        $record['fields'] = serialize($_POST);
                        //$this->firephp->info($record);
                        $this->db->where('ID',$object_ID);
                        $this->db->update('objects',$record);

                        if ($this->db->affected_rows() >= '0')
                        {
                            echo json_encode(array('action'=>true,'msg'=>'Successful edit operation.'));
                        }else
                        {
                            echo json_encode(array('action'=>FALSE, 'msg'=>'<p>An Error Occured.</p>')); 
                        }
                        break;
                }



            }

            /*switch($_POST['newObjectDialog_post_action']){

            case 'NEW':     $this->objects_model->create_post();
            break;

            case 'EDIT':    $this->objects_model->update_post();
            break;

            }*/

        }

        public function dropdown_check($str)
        {
            if ($str == '0')
            {
                $this->form_validation->set_message('dropdown_check', 'Please choose object <b>%s</b>!');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }

        function delete($post_ID){

            if($this->objects_model->delete_post($post_ID)){
                $this->view_all();
            }else{
                echo 'Error ocured';
                $this->view_all();
            }

        }

        public function form_view($type=NULL)
        {   

            // Todo: Order attributes with DB queries to mech order column, null order values should be last
            $this->load->helper('inflector');

            $q = 'SELECT oa.ID, oa.type, oa.custom, a.ID as att_ID, a.name, a.value, a.required, a.custom
            FROM object_attributes as oa
            LEFT JOIN attributes as a ON oa.attributes_ID = a.ID
            WHERE oa.type = "'.$_POST['type'].'"
            ORDER BY oa.order ASC, oa.custom ASC, oa.ID ASC
            ';

            $this->data['attributes'] = $this->db->query($q)->result_array();
            //$this->firephp->log($this->db->last_query());
            $data['counter'] = 0;
            $html = '';
            foreach ($this->data['attributes'] as $attribute):
            $data['attribute'] = $attribute;
            $data['post_action'] = "NEW";
            $data['counter']++;

            switch ($attribute['value']) {
                case 'descriptive data':
                    $html .= $this->load->view('templates/forms/elem_input', $data, TRUE); 
                    break;
                case 'yes/no':
                    $html .= $this->load->view('templates/forms/elem_checkbox', $data, TRUE); 
                    break;
            }

            endforeach;

            //$this->firephp->log($this->data['attributes']);
            echo json_encode(array('html'=>$html));
        }

        public function form_edit($type=NULL)
        {   

            // Todo: Order attributes with DB queries to mech order column, null order values should be last
            $this->load->helper('inflector');

            $q = 'SELECT oa.ID, oa.type, oa.custom, a.ID as att_ID, a.name, a.value, a.required, a.custom
            FROM object_attributes as oa
            LEFT JOIN attributes as a ON oa.attributes_ID = a.ID
            WHERE oa.type = "'.$_POST['type'].'"
            ORDER BY oa.order ASC, oa.custom ASC, oa.ID ASC
            ';

            //get attributes
            $this->data['attributes'] = $this->db->query($q)->result_array();
            //$this->firephp->log($this->db->last_query());

            //get object row
            $data['object'] = $this->objects_model->view_edit($_POST['id']);
            $data['fields'] = unserialize($data['object']['fields']);
            //$this->firephp->log($data['fields']);

            $data['counter'] = 0;
            $html = '';
            foreach ($this->data['attributes'] as $attribute):
            $data['attribute'] = $attribute;
            $data['post_action'] = "EDIT";
            $data['counter']++;

            switch ($attribute['value']) {
                case 'descriptive data':
                    $html .= $this->load->view('templates/forms/elem_input', $data, TRUE); 
                    break;
                case 'yes/no':
                    $html .= $this->load->view('templates/forms/elem_checkbox', $data, TRUE); 
                    break;
            }

            endforeach;

            //$this->firephp->log($this->data['attributes']);
            echo json_encode(array('html'=>$html));
        }

        public function attribute_view($type)
        {   
            $this->data['post_action'] = "NEW";
            $this->data['post_type'] = $type;   
            echo $this->load->view('objects/attributes/view_attributes',$this->data,TRUE);
        }

        public function attribute_new($type)
        {   
            $this->data['post_action'] = "NEW";
            $this->data['post_type'] = $type;   
            echo json_encode($this->load->view('objects/attributes/new_attributes',$this->data,TRUE));
        }

    }

    /* End of file Posts.php */
    /* Location: ./application/controllers/Posts.php */
